<template>
	<view class="container">
		<view class="form-container">
			<uv-form :model="formData" :rules="rules" ref="uForm" label-position="left" label-width="160">

				<!-- 基础信息 -->
				<view class="form-section">
					<view class="section-title">基础信息</view>

					<uv-form-item label="商品型号" prop="model" labelWidth="80" border-bottom>
						<uv-input v-model="formData.model" placeholder="请输入商品型号" border="none" />
					</uv-form-item>

					<uv-form-item label="商品产地" prop="origin" labelWidth="80" border-bottom>
						<uv-input v-model="formData.origin" placeholder="请输入商品产地" border="none" />
					</uv-form-item>

					<uv-form-item label="商品包装" prop="package" labelWidth="80" border-bottom>
						<uv-input v-model="formData.package" placeholder="请输入商品包装" border="none" />
					</uv-form-item>

					<uv-form-item label="商品类目" prop="category_id" labelWidth="80" @click="openCategoryPicker"
						border-bottom>
						<uv-input v-model="categoryDisplayName" disabled disabled-color="#ffffff" placeholder="请选择商品类目"
							border="none" />
						<uv-icon slot="right" name="arrow-right"></uv-icon>
					</uv-form-item>

					<uv-form-item label="商品品牌" prop="brand_id" labelWidth="80" @click="openBrandPicker" border-bottom>
						<uv-input v-model="brandDisplayName" disabled disabled-color="#ffffff" placeholder="点击获取品牌列表"
							border="none" />
						<uv-icon slot="right" name="arrow-right"></uv-icon>
					</uv-form-item>
				</view>

				<!-- 销售信息 -->
				<view class="form-section">
					<view class="section-title">销售信息</view>

					<view class="price-table-container">
						<view class="table-header">
							<view class="table-cell">价格</view>
							<view class="table-cell">库存</view>
							<view class="table-cell">重量(kg)</view>
						</view>
						<view class="table-row">
							<view class="table-cell">
								<uv-input v-model="formData.price" type="number" placeholder="0.00" border="none"
									class="table-input" />
							</view>
							<view class="table-cell">
								<uv-input v-model="formData.stock" type="number" placeholder="0" border="none"
									class="table-input" />
							</view>
							<view class="table-cell">
								<uv-input v-model="formData.weight" type="number" placeholder="0.00" border="none"
									class="table-input" />
							</view>
						</view>
					</view>
				</view>

				<!-- 图文描述 -->
				<view class="form-section">
					<view class="section-title">图文描述</view>

					<uv-form-item label="商品主图" prop="image" labelWidth="80" border-bottom>
						<view class="upload-wrapper">
							<!-- 商品主图上传 -->
							<wanl-upload v-model="mainImageList" :maxCount="1" uploadText="上传商品主图"
								tipText="支持jpg、png格式，大小不超过2M" @change="onMainImageChange"
								@upload-success="onMainUploadSuccess" @upload-error="onMainUploadError"
								@delete="onMainImageDelete">
							</wanl-upload>
						</view>
					</uv-form-item>

					<uv-form-item label="商品相册" prop="images" labelWidth="80" border-bottom>
						<!-- 商品相册上传 -->
						<wanl-upload v-model="galleryImageList" :maxCount="6" :multiple="true" uploadText="上传商品相册"
							tipText="支持jpg、png格式，大小不超过2M" @change="onGalleryImageChange"
							@upload-success="onGalleryUploadSuccess" @upload-error="onGalleryUploadError"
							@delete="onGalleryImageDelete">
						</wanl-upload>
					</uv-form-item>

					<uv-form-item label="商品详情" prop="content" labelWidth="80" border-bottom>
						<uv-textarea v-if="!isEdit" v-model="formData.content" placeholder="请输入商品详情" :maxlength="-1"
							count></uv-textarea>
						<uv-parse v-else :content="formData.content"></uv-parse>
					</uv-form-item>
				</view>

				<!-- 支付信息 -->
				<view class="form-section">
					<view class="section-title">支付信息</view>

					<uv-form-item label="库存计算方式" prop="stock_type" labelWidth="100" border-bottom>
						<uv-radio-group v-model="formData.stock_type">
							<uv-radio name="porder" activeColor="#fe5400" label="下单减库存"
								:customStyle="{margin: '8px'}" />
							<uv-radio name="payment" activeColor="#fe5400" label="付款减库存"
								:customStyle="{margin: '8px'}" />
						</uv-radio-group>
					</uv-form-item>
				</view>

				<!-- 物流信息 -->
				<view class="form-section">
					<view class="section-title">物流信息</view>

					<uv-form-item label="发货地" prop="place_of_shipment" labelWidth="100" @click="openPlacePicker"
						border-bottom>
						<uv-input v-model="placeName" disabled disabled-color="#ffffff" placeholder="点击选择发货地"
							border="none" />
						<uv-icon slot="right" name="arrow-right"></uv-icon>
					</uv-form-item>

					<uv-form-item label="运费模板" prop="freight_id" labelWidth="100" @click="openFreightPicker"
						border-bottom>
						<uv-input v-model="freightDisplayName" disabled disabled-color="#ffffff" placeholder="点击选择运费模板"
							border="none" />
						<uv-icon slot="right" name="arrow-right"></uv-icon>
					</uv-form-item>
				</view>

				<!-- 上架状态 -->
				<view class="form-section">
					<view class="section-title">上架状态</view>

					<uv-form-item label="上架状态" prop="status" labelWidth="100" border-bottom>
						<uv-radio-group v-model="formData.status">
							<uv-radio name="normal" activeColor="#fe5400" label="出售中商品"
								:customStyle="{margin: '8px'}" />
							<uv-radio name="hidden" activeColor="#fe5400" label="仓库中商品"
								:customStyle="{margin: '8px'}" />
						</uv-radio-group>
					</uv-form-item>
				</view>

			</uv-form>

			<!-- 操作按钮 -->
			<view class="form-actions">
				<uv-button type="primary" color="#fe5400" @click="submitForm"
					class="submit-btn">{{ isEdit ? '更新' : '提交' }}</uv-button>
			</view>

			<!-- 选择器组件 -->
			<uv-picker ref="categoryPicker" :columns="[categoryList]" :defaultIndex="categoryDefaultIndex"
				@confirm="onCategoryConfirm" keyName="name" />

			<uv-picker ref="brandPicker" :columns="[brandSelectList]" :defaultIndex="brandDefaultIndex"
				@confirm="onBrandConfirm" keyName="name" />

			<uv-picker ref="placePicker" :columns="[placeSelectList]" :defaultIndex="placeDefaultIndex"
				@confirm="onPlaceConfirm" keyName="name" />

			<uv-picker ref="freightPicker" :columns="[freightSelectList]" :defaultIndex="freightDefaultIndex"
				@confirm="onFreightConfirm" keyName="name" />

			<!-- 全局加载动画 -->
			<uv-loading-page :loading="showGlobalLoading" mode="circle" size="40"
				:loadingText="isEdit ? '加载商品信息中...' : '数据加载中...'" bgColor="rgba(0, 0, 0, 0.3)" color="#eeeeee"
				fontSize="14"></uv-loading-page>
			<uv-loading-page :loading="showSubmitLoading" mode="circle" size="40" loadingText="提交中..."
				bgColor="rgba(0, 0, 0, 0.3)" color="#eeeeee" fontSize="14"></uv-loading-page>
		</view>
	</view>
</template>

<script>
	import wanlUpload from '@/components/wanl-upload/wanl-upload.vue';
	export default {
		components: {
			wanlUpload
		},
		data() {
			return {
				isEdit: false,
				goodsId: null,
				showGlobalLoading: true,
				showSubmitLoading: false,
				formData: {
					model: '',
					origin: '',
					package: '',
					category_id: '',
					category_name: '', // 新增：保存完整分类路径名称
					brand_id: '',
					price: '',
					stock: '',
					weight: '',
					image: '',
					images: [],
					content: '',
					stock_type: 'porder',
					place_of_shipment: '',
					place_of_shipment_name: '',
					freight_id: '',
					status: 'normal'
				},
				// 表单验证规则
				rules: {
					model: [{
						required: true,
						message: '请输入商品型号',
						trigger: ['blur', 'change']
					}],
					origin: [{
						required: true,
						message: '请输入商品产地',
						trigger: ['blur', 'change']
					}],
					package: [{
						required: true,
						message: '请输入商品包装',
						trigger: ['blur', 'change']
					}],
					'formData.category_id': [{
						required: true,
						message: '请选择商品类目',
						trigger: ['blur', 'change']
					}],
					'formData.brand_id': [{
						required: true,
						message: '请选择商品品牌',
						trigger: ['blur', 'change']
					}],
					price: [{
							required: true,
							message: '请输入商品价格',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								if (!value || parseFloat(value) <= 0) {
									callback(new Error('请输入正确的价格'));
								} else {
									callback();
								}
							},
							trigger: ['blur', 'change']
						}
					],
					stock: [{
							required: true,
							message: '请输入商品库存',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								if (!value || parseInt(value) < 0) {
									callback(new Error('请输入正确的库存数量'));
								} else {
									callback();
								}
							},
							trigger: ['blur', 'change']
						}
					],
					weight: [{
						required: true,
						message: '请输入商品重量',
						trigger: ['blur', 'change']
					}],
					image: [{
						required: true,
						message: '请上传商品主图',
						trigger: ['blur', 'change']
					}],
					images: [{
						validator: (rule, value, callback) => {
							if (!value || value.length === 0) {
								callback(new Error('请上传商品相册'));
							} else {
								callback();
							}
						},
						trigger: ['change']
					}],
					content: [{
						required: true,
						message: '请输入商品详情',
						trigger: ['blur', 'change']
					}]
				},
				// 分类数据
				categoryList: [], // 一级分类
				// 其他数据列表
				brandList: [],
				areaList: [],
				freightList: [],
				// 图片列表
				mainImageList: [],
				galleryImageList: [],
				categoryDefaultIndex: [0],
				freightDefaultIndex: [0],
				placeDefaultIndex: [0],
				brandDefaultIndex: [0],
			};
		},
		computed: {
			// 类目选择显示文本
			categoryDisplayName() {
				const category = this.categoryList.find(item => item.id === this.formData.category_id);
				return this.formData.category_name || '请选择商品类目';
			},
			// 品牌选择显示文本
			brandDisplayName() {
				const brand = this.brandList.find(item => item.id === this.formData.brand_id);
				return brand ? brand.name : '点击获取品牌列表';
			},
			// 发货地选择显示文本
			placeName() {
				return this.formData.place_of_shipment_name || '点击选择发货地';
			},
			// 运费模板显示文本
			freightDisplayName() {
				const freight = this.freightList.find(item => item.id === this.formData.freight_id);
				return freight ? freight.name : '点击选择运费模板';
			},
			// 选择器数据格式
			brandSelectList() {
				return this.brandList;
			},
			placeSelectList() {
				return this.areaList;
			},
			freightSelectList() {
				return this.freightList;
			}
		},
		watch: {
			// 监听主图列表变化
			mainImageList: {
				handler(newVal) {
					const successImages = newVal.filter(item => item.status === 'success');
					if (successImages.length > 0) {
						this.formData.image = successImages[0].url;
					} else {
						this.formData.image = '';
					}
				},
				deep: true
			},
			// 监听相册列表变化
			galleryImageList: {
				handler(newVal) {
					const successImages = newVal.filter(item => item.status === 'success');
					this.formData.images = successImages.map(item => item.url);
				},
				deep: true
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			if (options.id) {
				this.isEdit = true;
				this.goodsId = options.id;
				uni.setNavigationBarTitle({
					title: '编辑商品'
				});
			}
			this.loadData();
		},
		methods: {
			// 初始化数据
			async loadData() {
				this.showGlobalLoading = true;
				try {
					await Promise.all([
						this.loadBrandList(),
						this.loadFreightList(),
						this.loadCategoryList(), // 修改分类加载
						this.loadAreaList()
					]);

					if (this.isEdit) {
						await this.loadGoodsDetail();
					}
				} catch (error) {
					console.error('加载数据失败:', error);
					this.$wanlshop.msg('加载数据失败');
				} finally {
					this.showGlobalLoading = false;
				}
			},

			// 加载商品详情
			async loadGoodsDetail() {
				try {
					const res = await uni.$uv.http.get('/supplier/getGoodsDetail', {
						params: {
							goods_id: this.goodsId
						}
					});

					if (res.res.code === 1) {
						const detail = res.res.data;

						// 填充表单数据
						this.formData = {
							model: detail.model || '',
							origin: detail.origin || '',
							package: detail.package || '',
							category_id: detail.category_id || '',
							category_name: this.getCategoryName(detail.category_id) || '',
							brand_id: detail.brand_id || '',
							price: detail.sku_items[0].price,
							stock: detail.sku_items[0].stock,
							weight: detail.sku_items[0].weigh,
							image: detail.image || '',
							images: detail.images ? detail.images.split(',') : [],
							content: detail.content || '',
							stock_type: detail.stock || 'porder',
							place_of_shipment: detail.place_of_shipment || '',
							place_of_shipment_name: this.getPlaceName(detail.place_of_shipment),
							freight_id: detail.freight_id || '',
							status: detail.status || 'normal'
						};

						// 设置图片列表
						if (detail.image) {
							this.mainImageList = [{
								url: detail.image,
								status: 'success'
							}];
						}

						if (detail.images) {
							const imageUrls = detail.images.split(',');
							this.galleryImageList = imageUrls.map(url => ({
								url: url,
								status: 'success'
							}));
						}
					} else {
						this.$wanlshop.msg(res.msg || '获取商品详情失败');
					}
				} catch (error) {
					console.error('加载商品详情失败:', error);
					this.$wanlshop.msg('加载商品详情失败');
				}
			},

			// 加载分类列表（修改为两级分类）
			async loadCategoryList() {
				try {
					// 加载一级分类
					const res = await uni.$uv.http.get('/supplier/getGoodsCategory', {
						params: {
							id: ''
						}
					});
					this.categoryList = res.data || [];
				} catch (error) {
					console.error('加载分类列表失败:', error);
					throw error;
				}
			},

			// 分类选择确认
			onCategoryConfirm(e) {
				if (e.value && e.value.length > 0) {
					// 处理可能只有一级分类的情况
					if (e.value.length === 1) {
						// 只有一级分类
						const firstCategory = e.value[0];
						this.formData.category_id = firstCategory.id;
						this.formData.category_name = firstCategory.name;
					} else if (e.value.length === 2) {
						// 有二级分类
						const firstCategory = e.value[0];
						const secondCategory = e.value[1];

						if (firstCategory && secondCategory) {
							this.formData.category_id = secondCategory.id;
							this.formData.category_name = `${firstCategory.name} / ${secondCategory.name}`;
						}
					}
				}
			},

			// 打开分类选择器
			openCategoryPicker() {
				if (this.formData.category_id > 0) {
					const index = this.categoryList.findIndex(item => item.id === this.formData.category_id);
					this.categoryDefaultIndex = [index];
				}
				this.$refs.categoryPicker.open();
			},

			// 获取分类名称
			getCategoryName(id) {
				if (!id) return '';
				const category = this.categoryList.find(item => item.id == id);
				return category ? category.name : '';
			},

			// 获取发货地名称
			getPlaceName(placeId) {
				if (!placeId) return '';
				const place = this.areaList.find(item => item.id == placeId);
				return place ? place.name : '';
			},

			// 加载地区列表
			async loadAreaList() {
				try {
					const res = await uni.$uv.http.get('/wanlshop/common/area');
					this.areaList = res.data;
				} catch (error) {
					console.error('加载地区列表失败:', error);
					throw error;
				}
			},

			// 加载品牌列表
			async loadBrandList() {
				try {
					const res = await uni.$uv.http.get('/wanlshop.product/brandList', {
						params: {
							show_all: false
						}
					});
					this.brandList = res.res.data;
				} catch (error) {
					console.error('加载品牌列表失败:', error);
					throw error;
				}
			},

			// 加载运费模板
			async loadFreightList() {
				try {
					const res = await uni.$uv.http.get('/supplier/getGoodsFreight');
					this.freightList = res.data;
				} catch (error) {
					console.error('加载运费模板失败:', error);
					throw error;
				}
			},

			openBrandPicker() {
				if (this.formData.brand_id > 0) {
					const index = this.brandSelectList.findIndex(item => item.id === this.formData.brand_id);
					this.brandDefaultIndex = [index];
				}
				this.$refs.brandPicker.open();
			},

			onBrandConfirm(e) {
				if (e.value && e.value.length > 0) {
					this.formData.brand_id = e.value[0].id;
				}
			},

			openFreightPicker() {
				if (this.formData.freight_id > 0) {
					const index = this.freightList.findIndex(item => item.id === this.formData.freight_id);
					this.freightDefaultIndex = [index];
				}
				this.$refs.freightPicker.open();
			},

			onFreightConfirm(e) {
				if (e.value && e.value.length > 0) {
					this.formData.freight_id = e.value[0].id;
				}
			},

			openPlacePicker() {
				if (this.formData.place_of_shipment > 0) {
					const index = this.placeSelectList.findIndex(item => item.id === this.formData.place_of_shipment);
					this.placeDefaultIndex = [index];
				}
				this.$refs.placePicker.open();
			},

			onPlaceConfirm(e) {
				if (e.value && e.value.length > 0) {
					this.formData.place_of_shipment = e.value[0].id;
					this.formData.place_of_shipment_name = e.value[0].name;
				}
			},

			// 主图变化
			onMainImageChange(fileList) {},

			// 主图上传成功
			onMainUploadSuccess(event) {
				this.$wanlshop.msg('主图上传成功');
			},

			// 主图上传失败
			onMainUploadError(event) {
				console.error('主图上传失败:', event);
				this.$wanlshop.msg('主图上传失败: ' + (event.error?.message || '未知错误'));
			},

			// 主图删除
			onMainImageDelete(event) {
				this.$wanlshop.msg('主图删除成功');
			},

			// 相册变化
			onGalleryImageChange(fileList) {},

			// 相册上传成功
			onGalleryUploadSuccess(event) {
				this.$wanlshop.msg('图片上传成功');
			},

			// 相册上传失败
			onGalleryUploadError(event) {
				console.error('相册上传失败:', event);
				this.$wanlshop.msg('图片上传失败: ' + (event.error?.message || '未知错误'));
			},

			// 相册删除
			onGalleryImageDelete(event) {
				this.$wanlshop.msg('删除成功');
			},

			// 提交表单
			async submitForm() {
				this.$refs.uForm.validate().then(async (valid) => {
					if (valid) {
						// if (!this.formData.image) {
						// 	this.$wanlshop.msg('请上传商品主图');
						// 	return;
						// }
						// if (!this.formData.images || this.formData.images.length === 0) {
						// 	this.$wanlshop.msg('请上传商品相册');
						// 	return;
						// }

						this.showSubmitLoading = true;

						try {
							const submitData = {
								...this.formData,
								price: parseFloat(this.formData.price),
								stock: this.formData.stock_type,
								stocks: parseInt(this.formData.stock),
								weigh: parseFloat(this.formData.weight),
								image: this.formData.image,
								images: this.formData.images.join(','),
								place_of_shipment: this.formData.place_of_shipment,
								sku: [{}],
								thumbnail: ''
							};

							if (this.isEdit) {
								submitData.goods_id = this.goodsId;
							}

							const api = this.isEdit ? '/supplier/editGoods' : '/supplier/addGoods';
							const res = await uni.$uv.http.post(api, submitData);

							if (res.res.code === 1) {
								this.$wanlshop.msg(this.isEdit ? '更新成功' : '添加成功');
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
							} else {
								this.$wanlshop.msg(res.res.msg || (this.isEdit ? '更新失败' : '添加失败'));
							}
						} catch (error) {
							console.error('提交失败:', error);
							this.$wanlshop.msg('网络错误，请重试');
						} finally {
							this.showSubmitLoading = false;
						}
					} else {
						this.$wanlshop.msg('请完善表单信息');
					}
				}).catch(errors => {
					console.log('表单验证失败:', errors);
					this.$wanlshop.msg('请完善表单信息');
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.form-container {
		background: #fff;
		border-radius: 8rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.form-section {
		margin-bottom: 40rpx;

		.section-title {
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 20rpx;
			padding-left: 10rpx;
			border-left: 6rpx solid #fe5400;
		}
	}

	.upload-wrapper {
		padding: 20rpx 0;
	}

	.error-tip {
		color: #fa5151;
		font-size: 24rpx;
		margin-top: 10rpx;
	}

	.price-table-container {
		border: 1rpx solid #e8e8e8;
		border-radius: 8rpx;
		overflow: hidden;

		.table-header {
			display: flex;
			background-color: #f5f7fa;

			.table-cell {
				flex: 1;
				padding: 20rpx;
				text-align: center;
				font-size: 26rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.table-row {
			display: flex;

			.table-cell {
				flex: 1;
				padding: 10rpx;

				.table-input {
					text-align: center;
				}
			}
		}
	}

	.form-actions {
		margin: 40rpx 0;

		.submit-btn {
			flex: 1;
			height: 80rpx;
			border-radius: 6rpx;
			font-size: 28rpx;
		}
	}

	/* 调整表单标签宽度 */
	:deep(.uv-form-item) {
		.uv-form-item__body {
			.uv-form-item__body__left__content {
				.uv-form-item__body__left__content__label {
					font-size: 28rpx;
					color: #333;
					width: 160rpx !important;
				}
			}
		}
	}

	/* 调整输入框样式 */
	:deep(.uv-input) {
		.uv-input__content {
			.uv-input__content__field {
				font-size: 28rpx;
			}
		}
	}
</style>